package com.sugar.queryinfo.module.business.service.infocomparison;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.sugar.queryinfo.framework.common.exception.ServiceException;
import com.sugar.queryinfo.module.business.api.bi.BackInvestApi;
import com.sugar.queryinfo.module.business.api.bi.dto.req.sjzwsj.ZCI040ReqVO;
import com.sugar.queryinfo.module.business.api.bi.dto.resp.ZCI040RespVO;
import com.sugar.queryinfo.module.business.controller.admin.userextend.vo.UserExtendSaveReqVO;
import com.sugar.queryinfo.module.business.dal.dataobject.apitypeinfo.ApiTypeInfoDO;
import com.sugar.queryinfo.module.business.service.apitypeinfo.ApiTypeInfoService;
import com.sugar.queryinfo.module.business.service.userextend.UserExtendService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.sugar.queryinfo.module.business.controller.admin.infocomparison.vo.*;
import com.sugar.queryinfo.module.business.dal.dataobject.infocomparison.InfoComparisonDO;
import com.sugar.queryinfo.framework.common.pojo.PageResult;
import com.sugar.queryinfo.framework.common.pojo.PageParam;
import com.sugar.queryinfo.framework.common.util.object.BeanUtils;

import com.sugar.queryinfo.module.business.dal.mysql.infocomparison.InfoComparisonMapper;

import static com.sugar.queryinfo.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.sugar.queryinfo.framework.common.util.collection.CollectionUtils.convertList;
import static com.sugar.queryinfo.framework.common.util.collection.CollectionUtils.diffList;
import static com.sugar.queryinfo.module.business.enums.ErrorCodeConstants.*;
import static com.sugar.queryinfo.module.business.enums.apitype.ApiTypeEnums.TYPE_ZNBD;

/**
 * 智能比对 Service 实现类
 *
 * @author Ysugar
 */
@Slf4j
@Service
@Validated
public class InfoComparisonServiceImpl implements InfoComparisonService {

    @Resource
    private InfoComparisonMapper infoComparisonMapper;
    @Resource
    private ApiTypeInfoService apiTypeInfoService;
    @Resource
    private UserExtendService userExtendService;
    @Resource
    private BackInvestApi backInvestApi;

    public List<InfoComparisonSaveRespVO> analysisContent(String content) {
        List<InfoComparisonSaveRespVO> respList = new ArrayList<>();

        String[] contentLineArr = content.split("\n");
        for (String contentLine : contentLineArr) {
            if (StrUtil.isNotBlank(contentLine)){
                String[] contentArr = contentLine.split("：");
                int length = contentArr.length;
                String nameMobileStr;
                switch (length){
                    case 2:
                        nameMobileStr = contentArr[1];
                        if (StrUtil.isNotBlank(nameMobileStr))
                            break;
                    case 1:
                        nameMobileStr = contentArr[0];
                        break;
                    default:
                        throw exception(INFO_COMPARISON_CONTENT_FORMAT_ERROR);
                }

                if (StrUtil.isBlank(nameMobileStr))
                    throw exception(INFO_COMPARISON_CONTENT_FORMAT_ERROR);

                // 获取手机号
                String mobile = findMobile(nameMobileStr);

                String name = nameMobileStr.replace(mobile, "").trim();

                /*String[] strArr = nameMobileStr.split(" ");
                if (strArr.length < 2)
                    throw exception(INFO_COMPARISON_CONTENT_FORMAT_ERROR);

                String name = strArr[0].trim();
                if (StrUtil.isBlank(name))
                    throw exception(INFO_COMPARISON_CONTENT_FORMAT_ERROR);
                String mobile = strArr[1].trim();
                if (StrUtil.isBlank(mobile))
                    throw exception(INFO_COMPARISON_CONTENT_FORMAT_ERROR);*/

                respList.add(new InfoComparisonSaveRespVO().setName(name).setMobile(mobile));
            }
        }

        if (CollUtil.isEmpty(respList))
            throw exception(INFO_COMPARISON_CONTENT_ANALYSIS_FAIL);

        return respList;
    }

    public static void main(String[] args) {
        System.out.println(findMobile("张三 13800000001"));
        System.out.println(findMobile("张三13800000001"));
        System.out.println(findMobile("张三     13800000001"));
        System.out.println(findMobile("  张三     13800000001    "));
    }

    private static String findMobile(String content) {
        String phoneRegex = "1[3-9]\\d{9}";
        Pattern phonePattern = Pattern.compile(phoneRegex);
        Matcher phoneMatcher = phonePattern.matcher(content);
        if (phoneMatcher.find()){
            return phoneMatcher.group();
        }
        throw exception(INFO_COMPARISON_CONTENT_FORMAT_ERROR);
    }

    @Override
    public List<InfoComparisonSaveRespVO> createInfoComparison(String content, Long userId, Long deptId) {
        List<InfoComparisonSaveRespVO> dataList = analysisContent(content);

        // 获取价格
        ApiTypeInfoDO apiTypeInfoDO = apiTypeInfoService.getApiPriceByType(TYPE_ZNBD);

        LocalDateTime now = LocalDateTime.now();

        for (InfoComparisonSaveRespVO respVO : dataList) {
            // 调用三方接口，校验数据
            ZCI040RespVO znbd = backInvestApi.znbd(new ZCI040ReqVO().setName(respVO.getName()).setPhone(respVO.getMobile()));
            respVO.setResult(znbd == null || "1".equals(znbd.getState()));

            // 扣费
            UserExtendSaveReqVO userExtendSaveReqVO = new UserExtendSaveReqVO();
            userExtendSaveReqVO.setUserId(userId).setDeptId(deptId)
                    .setType(false).setAmount(apiTypeInfoDO.getPrice())
                    .setTitle(apiTypeInfoDO.getName());
            userExtendService.updateUserBalance(userExtendSaveReqVO);

            // 插入
            InfoComparisonDO infoComparison = new InfoComparisonDO();
            infoComparison.setUserId(userId).setDeptId(deptId)
                    .setName(respVO.getName()).setMobile(respVO.getMobile())
                    .setResult(respVO.getResult()).setQueryTime(now);
            infoComparisonMapper.insert(infoComparison);
        }

        // 返回
        return dataList;
    }

    @Override
    public void deleteInfoComparison(Long id) {
        // 校验存在
        validateInfoComparisonExists(id);
        // 删除
        infoComparisonMapper.deleteById(id);
    }

    @Override
        public void deleteInfoComparisonListByIds(List<Long> ids) {
        // 删除
        infoComparisonMapper.deleteByIds(ids);
        }


    private void validateInfoComparisonExists(Long id) {
        if (infoComparisonMapper.selectById(id) == null) {
            throw exception(INFO_COMPARISON_NOT_EXISTS);
        }
    }

    @Override
    public InfoComparisonDO getInfoComparison(Long id) {
        return infoComparisonMapper.selectById(id);
    }

    @Override
    public PageResult<InfoComparisonDO> getInfoComparisonPage(InfoComparisonPageReqVO pageReqVO) {
        return infoComparisonMapper.selectPage(pageReqVO);
    }

}